package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.agent.ServiceBasicDataAgentDO;
import xcmg.device.dao.entity.company.EmployeeDO;
import xcmg.device.dao.mapper.agent.ServiceBasicDataAgentMapper;
import xcmg.device.dao.mapper.company.EmployeeMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.service.GenDocumentService;
import xcmg.device.service.agent.ServiceBasicDataAgentService;
import xcmg.device.service.vo.agent.ServiceBasicDataAgentVO;
import xcmg.device.service.vo.company.EmployeeVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.constants.ErrorCode;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Employee 后台接口实现类
 */
@Service
public class EmployeeService {

    private static final Logger logger = LoggerFactory.getLogger(EmployeeService.class);

    @Value("${xcmg.employeeJobCode:EMPLOYEE_JOB}")
    private String employeeJobCode;

    @Autowired
    private ServiceBasicDataAgentMapper serviceBasicDataAgentMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private GenDocumentService genDocumentService;

    @Autowired
    private ServiceBasicDataAgentService serviceBasicDataAgentService;

    @Autowired
    private FastGenClient fastGenClient;


    /**
     * 查询列表
     *
     * @param condition
     */
    public PageCommonVO<EmployeeVO> queryVoList(SearchCommonVO<EmployeeVO> condition) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        PageHelperPlus.orderBy("c.ORG_ID,e.Id desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<EmployeeVO> voList = employeeMapper.queryVoList(condition.getFilters());
        if (CollectionUtils.isNotEmpty(voList)) {
            Map<String, String> jobMap = queryJobIdNameMap(null);
            for (EmployeeVO vvo : voList) {
                if (MapUtils.isNotEmpty(jobMap) && StringUtils.isNotBlank(vvo.getJobId())) {
                    vvo.setLatestJobName(jobMap.get(vvo.getJobId()));
                }
            }
        }
        pageCommonVO.setPageInfo(new PageInfo(voList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 查询员工岗位的字典信息
     */
    public List<ServiceBasicDataAgentVO> queryJobList(String orgId) {
        ServiceBasicDataAgentVO vo = new ServiceBasicDataAgentVO();
        vo.setpCode(employeeJobCode);
        if (StringUtils.isNotBlank(orgId)) {
            vo.setOrgId(orgId);
        }
        return serviceBasicDataAgentService.queryList(vo);
    }

    public Map<String, String> queryJobIdNameMap(String orgId) {
        List<ServiceBasicDataAgentVO> ll = queryJobList(orgId);
        Map<String, String> map = ll.parallelStream().collect(Collectors.toMap(ServiceBasicDataAgentVO::getId, a -> a.getName(), (k1, k2) -> k1));
        return map;
    }

    /**
     * 查询员工岗位的字典信息
     */
    public List<ServiceBasicDataAgentVO> queryJobListByMap(Map<String, Object> param) {
        param.put("pCode", employeeJobCode);
        List<ServiceBasicDataAgentDO> ddoList = serviceBasicDataAgentMapper.queryJobListByMap(param);
        if (CollectionUtils.isNotEmpty(ddoList)) {
            return BeanUtil.do2bo4List(ddoList, ServiceBasicDataAgentVO.class);
        }
        return Collections.EMPTY_LIST;
    }

    public Map<String, ServiceBasicDataAgentVO> queryJobListByMap(String orgId) {
        Map<String, ServiceBasicDataAgentVO> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        //此时岗位为所有主机厂家共享，不传orgId
        List<ServiceBasicDataAgentVO> ll = queryJobListByMap(param);
        if (CollectionUtils.isNotEmpty(ll)) {
            for (ServiceBasicDataAgentVO m : ll) {
                result.put(m.getName(), m);
            }
        }
        return result;
    }

    /**
     * 查询列表
     *
     * @param vo
     */
    public List<EmployeeDO> queryList(EmployeeVO vo) {
        return employeeMapper.queryList(vo);
    }


    /**
     * 查询单条记录
     *
     * @param id
     */
    public EmployeeDO queryById(String id) {
        EmployeeVO vo = new EmployeeVO();
        vo.setId(id);
        List<EmployeeDO> list = queryList(vo);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 保存数据
     *
     * @param employeeVO
     * @param userId
     * @param userName
     * @param orgId
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode save(EmployeeVO employeeVO, String userId, String userName, String orgId) throws Exception {
        doSave(employeeVO, userId, userName, orgId);
        return ErrorCode.Success;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode batchSave(List<EmployeeVO> list, String userId, String userName, String orgId) throws Exception {
        for (EmployeeVO employeeVO : list) {
            doSave(employeeVO, userId, userName, orgId);
        }
        return ErrorCode.Success;
    }

    /**
     * 根据状态，等信息保存数据
     *
     * @param employeeVO
     * @param userId
     * @param userName
     * @param orgId
     */
    private void doSave(EmployeeVO employeeVO, String userId, String userName, String orgId) throws Exception {
        EmployeeDO employeeDO = BeanUtil.do2bo(employeeVO, EmployeeDO.class);
        Map<String, String> jobMap = queryJobIdNameMap(null);
        if (MapUtils.isNotEmpty(jobMap) && StringUtils.isNotBlank(employeeDO.getJobId())) {
            employeeDO.setJob(jobMap.get(employeeVO.getJobId()));
        }
        boolean isSuccess = false;
        employeeDO.setUpdateName(userName);
        employeeDO.setUpdateDate(new Date());
        if (StringUtils.isBlank(employeeDO.getId())) {
            employeeDO.setCreateName(userName);
            employeeDO.setOrgId(orgId);
            employeeDO.setCreateDate(new Date());
            employeeDO.setId(genId());
            employeeDO.setIsDel(0);
            logger.info("新增操作，employeeDO:{}", employeeDO);
            isSuccess = employeeMapper.insert(employeeDO) > 0;
        } else {
            logger.info("编辑操作，employeeDO:{}", employeeDO);
            isSuccess = employeeMapper.updateByPrimaryKeySelective(employeeDO) > 0;
        }
        if (!isSuccess) {
            throw new Exception("保存记录失败");
        }
    }


    /**
     * 批量删除
     *
     * @param ids
     */
    @Transactional
    public int batchDelete(List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        }
        int i = 0;
        for (String id : ids) {
            i = +employeeMapper.deleteByPrimaryKeySelective(id);
        }
        return i;
    }

    @Transactional
    public ErrorCode delete(ArrayList<String> ids, String orgId) {
        if (CollectionUtils.isEmpty(ids)) {
            return ErrorCode.IllegalArument;
        }
        int i = 0;
        for (String id : ids) {
            EmployeeDO employeeDO = new EmployeeDO();
            employeeDO.setId(id);
            employeeDO.setIsDel(1);
            i = +employeeMapper.updateByPrimaryKeySelective(employeeDO);
        }
        if (i > 0) {
            return ErrorCode.Success;
        }
        return ErrorCode.Failure;
    }

    /**
     * 生成id
     *
     * @return
     * @throws Exception
     */
    private String genId() throws Exception {
        ActionResult<String> genResult = fastGenClient.textGuid();
        if (genResult.getCode() != ErrorCode.Success.getCode()) {
            throw new Exception("生成ID异常");
        }
        return genResult.getValue();
    }

    public Integer countByJob(String orgId, String jobId) {
        Integer countByJob = employeeMapper.countByJob(orgId, jobId);
        if (null != countByJob) {
            return countByJob;
        }
        return 0;
    }

}
